<script lang="ts" setup>
  import { GamePlayResult, GamePlay, Game } from '@/types/game';
  import { onMounted, ref } from 'vue';
  import { Form } from '@arco-design/web-vue';
  import type { GameEnrollType } from '@/types/game';
  import { getGameEnrollTypes, addGamePlay, getAllPlayTypes } from '@/api/game';
  import CheckGroupBio from '@/components/check-group-bio.vue';

  const props = defineProps<{
    gameInfo: Game;
    gameId: string;
    isParent: boolean;
  }>();

  const emit = defineEmits(['close']);

  const gameEnrollTypes = ref<GameEnrollType[]>([]);

  const initGameEnrollData = async () => {
    const res = await getGameEnrollTypes(props.gameId);
    gameEnrollTypes.value = res.data.data;
  };

  const gamePlayTypes = ref<GamePlay[]>([]);

  const data = ref<Partial<GamePlayResult>>({
    gameId: props.gameId,
  });

  const saving = ref(false);
  const formRef = ref<InstanceType<typeof Form> | null>(null);
  const handleSubmit = async () => {
    if (formRef.value) {
      const validateResult = await formRef.value.validate();
      if (!validateResult) {
        try {
          saving.value = true;
          const dataToSaved = {
            ...data.value,
          };

          if (
            props.gameInfo.gameType === 1 &&
            props.gameInfo.childGameCount === 1
          ) {
            delete dataToSaved.enrollType;
          }
          // 配对赛不用区分男女，不区分球员类型，没有组别之分
          if (dataToSaved.calType === 3) {
            dataToSaved.sex = 2;
            dataToSaved.userType = 1;
            delete dataToSaved.enrollType;
            // 团队赛，没有分区
          } else if (dataToSaved.calType === 2) {
            dataToSaved.groupBy = 1;
          }

          await addGamePlay(dataToSaved);
          emit('close', true);
        } finally {
          saving.value = false;
        }
      }
    }
  };

  onMounted(async () => {
    try {
      const res = await getAllPlayTypes();
      gamePlayTypes.value = res.data.data;
      await initGameEnrollData();
    } finally {
      // do nothing
    }
  });

  const handleCalTypeChanged = () => {
    if (data.value.calType === 3) {
      data.value.playId = 2;
    }
  };
</script>

<template>
  <a-modal
    title="添加玩法"
    :width="500"
    visible
    :ok-loading="saving"
    @cancel="emit('close', false)"
    @before-ok="handleSubmit"
  >
    <a-form ref="formRef" :model="data" layout="vertical">
      <a-form-item
        label="成绩单名称"
        field="name"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-input v-model="data.name" />
      </a-form-item>
      <a-form-item
        label="类型"
        field="calType"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-radio-group
          v-model="data.calType"
          :options="[
            { label: '个人', value: 1 },
            {
              label: '团队',
              value: 2, // 多阶段赛事，不支持配对
              disabled: gameInfo.childGameCount === 2,
            },
            {
              label: '配对',
              value: 3,
              // 多阶段赛事，不支持配对
              disabled: gameInfo.childGameCount === 2,
            },
          ]"
          @change="handleCalTypeChanged as any"
        />
      </a-form-item>
      <a-form-item
        label="玩法"
        field="playId"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-select
          v-model="data.playId"
          :options="
            gamePlayTypes.map((i) => ({
              label: i.name,
              value: i.id,
              disabled: i.id !== 2 && data.calType === 3,
            }))
          "
        />
      </a-form-item>
      <!-- 父比赛不支持组别划分 -->
      <a-form-item
        v-if="
          gameInfo.childGameCount === 2 || (!isParent && data.calType !== 3)
        "
        label="适用组别"
        field="enrollType"
      >
        <a-select
          v-model="data.enrollType"
          allow-clear
          :options="
            gameEnrollTypes.map((i) => ({ label: i.name, value: i.id }))
          "
        />
      </a-form-item>
      <!-- 配对赛不区分男女 -->
      <a-form-item
        v-if="data.calType === 1 || data.calType === 2"
        label="适用性别"
        field="sex"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-radio-group
          v-model="data.sex"
          :options="[
            { label: '仅限男性', value: 1 },
            { label: '仅限女性', value: 0 },
            { label: '男女均可', value: 2 },
          ]"
        />
      </a-form-item>
      <a-form-item
        v-if="data.calType === 1 || data.calType === 2"
        label="球员类型"
        field="userType"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <CheckGroupBio
          v-model="data.userType"
          :options="[
            { label: '青少年', value: 0b0000001 },
            { label: '成人', value: 0b0000010 },
            { label: '教练', value: 0b0000100 },
          ]"
        />
      </a-form-item>
      <a-form-item
        v-if="data.calType === 1 || data.calType === 2"
        label="是否包括虚拟球员"
        field="withUnreal"
      >
        <a-radio-group
          v-model="data.withUnreal"
          :options="[
            { label: '不包括', value: 0 },
            { label: '包括', value: 1 },
          ]"
        />
      </a-form-item>
      <a-form-item
        v-if="data.calType !== 2 && gameInfo.childGameCount !== 2"
        label="分区方式"
        field="groupBy"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-radio-group
          v-model="data.groupBy"
          :options="[
            { label: '不分区', value: 1 },
            { label: '按省份分区', value: 2 },
            { label: '按球场分区', value: 3 },
          ]"
        />
      </a-form-item>
      <!-- 团队赛时，以什么作为团队依据（1：省份；2：城市；3：球场） -->
      <a-form-item
        v-if="data.calType == 2 && gameInfo.childGameCount !== 2"
        label="组队依据"
        field="teamBy"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-radio-group
          v-model="data.teamBy"
          :options="[
            { label: '省份', value: 1 },
            { label: '城市', value: 2 },
            { label: '球场', value: 3 },
          ]"
        />
      </a-form-item>
      <a-form-item
        v-if="data.calType == 2 && gameInfo.childGameCount !== 2"
        label="取成绩前N名"
        field="teamPlayerCount"
        :rules="[{ required: true, message: '不能为空' }]"
      >
        <a-input-number
          v-model="data.teamPlayerCount"
          :min="1"
          :step="1"
          :precision="0"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
